const app = getApp()
import mqtt from "../../components/utils/mqtt.min";

Page({
  data: {
    key: "1b79dfa058454105be487a4d510ac5aa",// 用户密钥
    ledtopic: "ledtopic",// 控制LED的主题
    temperature_topic: "tempertopic",//温度
    humidity_topic: "humidtopic",//湿度
    airQuality_topic: "airQualtopic",//空气质量
    lightIntensity_topic: "lighttopic",//光敏
    smokeIntensity_topic: "smoketopic",//烟雾
    mqtt_user: "iot601_wu",
    mqtt_pwd: "1@3fS6",
    device_status: "离线", // MQTT连接状态
    led_status: "关闭", // LED状态
    temperature: "未知", // 温度
    humidity: "未知", // 湿度
    airQuality: "未知", // 空气质量
    lightIntensity: "未知", // 光敏模拟量
    smokeIntensity: "未知", // 烟雾检测模拟量
  },
  client: null, // MQTT客户端  
  onLoad: function () {
    // 监听MQTT
    console.log("监听MQTT");
    this.mqttConnect();
  },
  // MQTT SETTING ---------------------------------------------------- START
  mqttConnect: function () {
    var that = this;
    let ip = 'bemfa.com:9504/wss'
    // MQTT连接的配置  
    var ESP8266_options = {
      keepalive: 60,// 60s，表示心跳间隔
      ssl: false,
      clean: true,// cleanSession不保持持久会话
      protocolVersion: 4,// MQTT v3.1.1
      clientId: this.data.key,//clientID
      // username: this.data.mqtt_user,
      // password: this.data.mqtt_pwd,
      reconnectPeriod: 4 * 1000,
      connecTimeout: 3 * 1000,
    }
    // 初始化mqtt连接
    this.client = mqtt.connect('wxs://' + ip, ESP8266_options);
    // 连接MQTT服务器
    this.client.on("connect", function () {
      console.log("连接成功,订阅外部消息");
      // 订阅外部消息
      that.setData({ device_status: "在线" });
    });
    // 接收消息
    this.client.on('message', this.handleMqttMessage);
    // 断线重连
    this.client.on("reconnect", function () {
      console.log("重新连接")
      that.setData({ device_status: "重新连接" })
    });
    // 连接失败
    this.client.on('error', function (err) {
      console.log("链接失败", err)
      that.setData({
        device_status: "重新连接"
      })
    });
    // 连接断开
    this.client.on('end', function () {
      console.log("连接断开")
      that.setData({
        device_status: "连接断开"
      })
    });
  },
  // MQTT SETTING ---------------------------------------------------- END
  //订阅所有主题
  subscribeTopics: function () {
    const topics = [
      this.data.ledtopic,
      this.data.tempertopic,
      this.data.humidtopic,
      this.data.airQualtopic,
      this.data.lighttopic,
      this.data.smoketopic,
    ];
    this.client.subscribe(topics, (err) => {
      if (err) {
        console.log(err);
      }
    });
  },
  handleMqttMessage: function (topic, message) {
    const msg = message.toString();
    if (topic === this.data.ledtopic) {
      this.setData({ ledStatus: msg === 'on' ? '打开' : '关闭' });
    } else if (topic === this.data.tempertopic) {
      console.log(this.data.tempertopic);
      console.log(msg);
      this.setData({ temperature: parseInt(msg) });
    } else if (topic === this.data.humidtopic) {
      this.setData({ humidity: parseInt(msg) });
    } else if (topic === this.data.airQualtopic) {
      this.setData({ airQuality: parseInt(msg) });
    } else if (topic === this.data.lighttopic) {
      this.setData({ lightIntensity: parseInt(msg) });
    } else if (topic === this.data.smoketopic) {
      this.setData({ smoketopic: parseInt(msg) });
    }
  },
  toggleLED: function () {
    if (this.data.client.connected) {
      let newStatus = this.data.client.powerstatus === '打开' ? "关闭" : "打开"
      let message = newStatus === "打开" ? "ON" : "OFF"
      this.data.client.publish(this.data.ledtopic, message)
      this.setData({powerstatus: newStatus, })
    } else {
      console.log("MQTT 客户端错误，发送信息失败")
    }
  }
})